package com.itxiaowu.controller;

import com.itxiaowu.constant.MessageConstant;
import com.itxiaowu.entity.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private JedisPool jedisPool;

    /**
     *  获得登录的用户名
     */
    @RequestMapping("/getusername.do")
    public Result getUserName(){

        try{
                                // 安全框架           获得上下文域      获得认证信息        获得认证信息中的user数据
            User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();

            String username = user.getUsername();

            BCryptPasswordEncoder bc = new BCryptPasswordEncoder();
            boolean b = bc.matches("admin", user.getPassword());
            System.out.println(b);

            return new Result(true,MessageConstant.GET_USERNAME_SUCCESS,username);
        }catch (Exception e){

            return new Result(false, MessageConstant.GET_USERNAME_FAIL);
        }
    }
    @RequestMapping("/logout.do")
    public void loginOut(){
        // 清除浏览数据
        Jedis jedis = jedisPool.getResource();
        User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        jedis.del("menuList" +user.getUsername());



        jedis.close();
    }


//    public static void main(String[] args) {
//        BCryptPasswordEncoder bc = new BCryptPasswordEncoder();
//
//        String admin = bc.encode("admin");
//        System.out.println(admin);
//        String admin1 = bc.encode("admin");
//        System.out.println(admin1);
//        boolean b = bc.matches("admin", "$2a$10$u/BcsUUqZNWUxdmDhbnoeeobJy6IBsL1Gn/S0dMxI2RbSgnMKJ.4a");
//        System.out.println(b);
//    }

}
